package com.gmail.mariska.martin.jpa;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.log4j.Logger;

/**
 * Singleton na perzistetni vrstvu
 * 
 * @author MAR
 * 
 */
public class Perzistence {
	static final Logger logger = Logger.getLogger(Perzistence.class);
	EntityManagerFactory emf = null;
	private static Perzistence INSTANCE = null;
	private final static Object mutex = new Object();

	private Perzistence() {
		// singleton
		// init();
	}

	public void init() {
		if (emf == null) {
			try {
				// Open a database connection (create a new database if it doesn't exist yet):
				Map<String, String> properties = new HashMap<String, String>();
				properties.put("javax.persistence.jdbc.user", "admin");
				properties.put("javax.persistence.jdbc.password", "admin");
				emf = Persistence.createEntityManagerFactory("V:\\.db\\dogDB.odb", properties);
				logger.info("Persistence creates EMF > " + emf.toString());
			} catch (Exception e) {
				logger.error(e, e);
			}
		}
		logger.info("Persistence initialized.");
	}

	public void destroy() {
		if (emf != null) {
			if (emf.isOpen()) {
				emf.close();
			}
		}
		logger.info("Persistence destroyed.");
	}

	public EntityManager createEntityManager() {
		return emf.createEntityManager();
	}

	public static Perzistence getInstance() {
		if (INSTANCE == null) {
			synchronized (mutex) {
				if (INSTANCE == null) {
					INSTANCE = new Perzistence();
				}
			}
		}
		return INSTANCE;
	}

}
